import { createRouter, createWebHashHistory } from "vue-router";
import { ElNotification } from "element-plus";
import Cache from "@/utils/Cache";
const routes = [
  {
    path: "/",
    name: "home",
    component: () => import("@/views/home"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login"),
  },
  {
    path: "/game",
    name: "game",
    component: () => import("@/views/game"),
  },
  {
    path: "/my",
    name: "my",
    component: () => import("@/views/my"),
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/404"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 判断用户是否存在、登录状态
router.beforeEach((to, from, next) => {
  if (to.fullPath === "/my") {
    if (!Cache.getItem("user")) {
      ElNotification({
        title: "请先进行登录！",
        message: "跳转至登录页面",
        type: "warning",
      });
      next("/login");
    } else {
      const user = Cache.getItem("user");
      if (
        Math.floor(Date.now() / 1000) - Math.floor(user.createTime / 1000) >=
        10 * 60
      ) {
        ElNotification({
          title: "登录已过期！",
          message: "跳转至登录页面",
          type: "warning",
        });
        next("/login");
      } else {
        next();
      }
    }
  } else next();
});

export default router;
